#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <zlib.h>
//#include <sys/lib.h>
#include <string.h>

#define GZ_BUF_SIZE 1014*1024

int gzLoad( char* gzfile, char* retfile, char* reffile ){

    gzFile gzfp = gzopen( gzfile, "rb" );
    FILE* retfp = fopen(retfile, "wb+");
    FILE* reffp = fopen(reffile, "wb+");

    if( !gzfp ) {
        printf("open gzfile error");
        return -1;
    } else if ( !retfp ) {
        printf("open retfile error");
        return -1;
    } else if ( !reffp ) {
        printf("open reffile error");
        return -1;
    }

    long offsetend = 0;
    long sumline = 0;
    unsigned char buf[GZ_BUF_SIZE];
    char long2charbuf[64];
    while( gzgets( gzfp, buf, GZ_BUF_SIZE ) )
    {
        sumline ++;
        if( !(sumline % 4) ) {
            offsetend = gztell( gzfp );
            fwrite( &offsetend, sizeof(long), 1, retfp);
            fprintf( reffp, "%ld\n", offsetend);
        }
    }

    fclose( retfp );
    fclose( reffp );
    gzclose( gzfp );
    return 1;
}

int main(int argc,char** argv)
{
    double  start, finish;
    char *retfile = (char *)malloc(1024);
    char *reffile = (char *)malloc(1024);  
    
    start = clock();//取开始时间
    if( argc != 2 )
    {
        printf("./gzfileindex gzfile\n");
        return -1;
    }
    strcpy( retfile, argv[1] );
    strncat( retfile, ".bi", strlen(".bi") );
    strcpy( reffile, argv[1] );
    strncat( reffile, ".ti", strlen(".ti") );    

    if( gzLoad( argv[1], retfile, reffile ) ){
        printf("success");
    } else {
        printf("gzLoad Error");
        return -1;
    }
    finish = clock();//取结束时间
    printf( "%f seconds\n",(finish - start) / CLOCKS_PER_SEC);
    return 0;
}
